<template>
  <a-spin :spinning="confirmLoading" class="contain">
    <step-components :steps="components.map((v) => v.title)" :current="current" />
    <component
      class="component-action"
      ref="refComponent"
      :current="current"
      :value="setValue()"
      :is="allComps[getComponents('componentsName')]"
    />
    <div class="submit-action">
      <a-space class="btn-div" :size="14">
        <a-button type="primary" v-if="current < components.length" @click="next"> 下一步 </a-button>
        <a-button v-if="current > 1" @click="prev"> 上一步 </a-button>
        <a-button type="primary" @click="onEditSubmit"> 保存并退出 </a-button>
        <template v-if="current === components.length">
          <a-button type="primary" @click="onSubmit"> 提交 </a-button>
          <a-tooltip placement="topLeft" title="注：提交后生成全息档案，不可再编辑，请谨慎操作！">
            <a-icon type="question-circle" />
          </a-tooltip>
        </template>
      </a-space>
    </div>
  </a-spin>
</template>

<script>
import { getSocialPersonInfo, addSocialPerson } from '@/api/sjsk/personService'
import allComps, { components } from './modules/index'
import stepComponents from './modules/step.vue'
export default {
  inject: ['closeCurrent'],
  components: { stepComponents },
  data() {
    return {
      current: 1,
      allComps: allComps,
      components: components,
      confirmLoading: false,
      socialPersonAddVO: {},
      id: null
    }
  },
  created() {
    this.getRouteQuery(this.$route)
  },
  watch: {
    $route(data) {
      this.getRouteQuery(data)
    },
    id(value) {
      this.getSocialPersonInfo(value)
    },
    'socialPersonAddVO.socialRelationList':{
      deep: true,
      handler(val){
        this.socialPersonAddVO.helpPlanVO.socialRelationList = val
      }
    }
  },
  methods: {
    getComponents(key) {
      let item = this.components.find((obj) => {
        return obj.type == this.current
      })
      return item[key]
    },
    next() {
      this.getValue()
      //actionPlans、helpGroupList
      if (this.current == 1 || this.current == 4 || this.current == 5) {
        this.onValidate()
        // Object.keys(this.socialPersonAddVO).length > 0 && this.socialPersonAddVO['helpPlanVO'] && this.socialPersonAddVO['helpPlanVO'].helpGroupList.length === 0
        // Object.keys(this.socialPersonAddVO).length > 0 && this.socialPersonAddVO['helpPlanVO'] && this.socialPersonAddVO['helpPlanVO'].actionPlans.length === 0
      } else {
        if (
          this.current === 2 &&
          Object.keys(this.socialPersonAddVO).length > 0 &&
          this.socialPersonAddVO['socialRelationList'] &&
          this.socialPersonAddVO['socialRelationList'].length === 0
        ) {
          this.$message.warn('请至少新增一条数据！')
          return
        } else {
          this.current++
          this.setValue()
        }
      }
      console.log(this.socialPersonAddVO);
    },
    prev() {
      this.getValue()
      this.current--
      this.setValue()
    },
    onValidate() {
      const { refComponent } = this.$refs
      refComponent.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.current++
          this.setValue()
        } else {
          return false
        }
      })
    },
    onEditSubmit() {
      this.getValue()
      if (this.current == 1 || this.current == 4 || this.current == 5) {
        // this.onValidate()
        const { refComponent } = this.$refs
        console.log(refComponent);
        refComponent.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.$set(this.socialPersonAddVO.socialPersonInfoVO, 'isSubmit', 2)  //是否提交 1：是（提交） 2：否（保存）
            this.addSocialPerson()
          } else {
            return false
          }
        })
      } 
      else {
        if (
          this.current === 2 &&
          Object.keys(this.socialPersonAddVO).length > 0 &&
          this.socialPersonAddVO['socialRelationList'] &&
          this.socialPersonAddVO['socialRelationList'].length === 0
        ) {
          this.$message.warn('请至少新增一条数据！')
          return
        } else {
          this.$set(this.socialPersonAddVO.socialPersonInfoVO, 'isSubmit', 2)  //是否提交 1：是（提交） 2：否（保存）
          this.addSocialPerson()
        }
      }
      // const { refComponent } = this.$refs
      // refComponent.$refs.ruleForm.validate((valid) => {
      //   if (valid) {
      //     this.addSocialPerson()
      //     console.log(refComponent.formParam)
      //   } else {
      //     return false
      //   }
      // })
    },
    onSubmit() {
      this.getValue()
      // const { refComponent } = this.$refs
      // refComponent.$refs.ruleForm.validate((valid) => {
      //   if (valid) {
        this.$set(this.socialPersonAddVO.socialPersonInfoVO, 'isSubmit', 1)  //是否提交 1：是（提交） 2：否（保存）
        this.addSocialPerson()
      //   } else {
      //     return false
      //   }
      // })
    },
    onCancle() {
      // 注意：以下代码必须存在
      // inject:['closeCurrent'],
      this.closeCurrent()
      this.$router.push({ path: '/drugUsers/connection-list' })
    },
    getValue() {
      const { refComponent } = this.$refs
      let ObjectValue = {},
        ArrayValue = []
      if (this.current === 1) {
        ObjectValue = refComponent.model
        this.$set(this.socialPersonAddVO, 'socialPersonInfoVO', ObjectValue)
        if (Object.keys(ObjectValue).length > 0 && ObjectValue.socialDrugKeywordList) {
          this.$set(this.socialPersonAddVO, 'socialDrugKeywordList', ObjectValue.socialDrugKeywordList)
        }
      }
      if (this.current === 2) {
        ArrayValue = refComponent.pageData
        console.log(ArrayValue);
        this.$set(this.socialPersonAddVO, 'socialRelationList', ArrayValue)
      }
      if (this.current === 3) {
        ArrayValue = refComponent.pageData
        this.$set(this.socialPersonAddVO, 'otherCriminalRecordList', ArrayValue)
      }
      if (this.current === 4) {
        ObjectValue = refComponent.model
        this.$set(this.socialPersonAddVO, 'socialLocationInfo', ObjectValue)
      }
      if (this.current === 5) {
        ObjectValue = refComponent.model
        this.$set(this.socialPersonAddVO, 'helpPlanVO', ObjectValue)
      }
    },
    setValue() {
      let ObjectValue = {},
        ArrayValue = []
      if ( this.current === 1 && Object.keys(this.socialPersonAddVO).length > 0 && this.socialPersonAddVO['socialPersonInfoVO'] ) {
        const { socialDrugKeywordList } = this.socialPersonAddVO
        let InfoVO = { socialDrugKeywordList }
        ObjectValue = Object.assign({}, this.socialPersonAddVO['socialPersonInfoVO'], InfoVO)
      }
      if ( this.current === 2 && Object.keys(this.socialPersonAddVO).length > 0 && this.socialPersonAddVO['socialRelationList'] ) {
        
        ArrayValue = this.socialPersonAddVO['socialRelationList']
      }
      if ( this.current === 3 && Object.keys(this.socialPersonAddVO).length > 0 && this.socialPersonAddVO['otherCriminalRecordList'] ) {
        ArrayValue = this.socialPersonAddVO['otherCriminalRecordList']
      }
      if (this.current === 4 && Object.keys(this.socialPersonAddVO).length > 0) {
        const { socialPersonInfoVO } = this.socialPersonAddVO
        let InfoVO = { liveAddress: socialPersonInfoVO.currentAddress,
                        workUnit: socialPersonInfoVO.workUnit
                      }
        if (this.socialPersonAddVO['socialLocationInfo']) {
          ObjectValue = Object.assign({}, this.socialPersonAddVO['socialLocationInfo'], InfoVO)
        } else {
          ObjectValue = Object.assign({}, InfoVO)
        }
      }
      if (this.current === 5 && Object.keys(this.socialPersonAddVO).length > 0 && this.socialPersonAddVO['helpPlanVO']) {
        ObjectValue = Object.assign({}, this.socialPersonAddVO['helpPlanVO'])
      }
      if (this.current === 6 && Object.keys(this.socialPersonAddVO).length > 0) {
        let outDates = this.socialPersonAddVO['socialDrugKeywordList'].filter(col => col.value === 4)
        let InfoVO = { outDate: outDates.length>0?outDates[0].endDate: '', personType: this.socialPersonAddVO['socialPersonInfoVO'].personType  }
        ObjectValue = Object.assign({}, InfoVO)
      }
      let value =
        this.current === 1 || this.current === 4 || this.current === 5 || this.current === 6 ? ObjectValue : ArrayValue
      // console.log(this.current, value)
      return value
    },
    // 新增、编辑操作
    addSocialPerson() {
      // this.confirmLoading = true
      // if(Object.keys(this.socialPersonAddVO).length>0 && this.socialPersonAddVO['helpPlanVO']) {
      //   let actionPlans = this.socialPersonAddVO['helpPlanVO'].actionPlans
      //   this.$set(this.socialPersonAddVO['helpPlanVO'].addScheduleDTO, 'actionPlans', actionPlans)
      // }

      addSocialPerson(this.socialPersonAddVO)
        .then((res) => {
          this.confirmLoading = false
          if (res.success) {
            this.$message.success(res.message)
            this.onCancle()
          } else {
            this.$message.warn(res.message)
          }
        })
        .catch((e) => {
          this.$message.warn('请求失败！')
          this.confirmLoading = false
        })
    },
    // 获取个人信息详情
    getSocialPersonInfo(id) {
      this.confirmLoading = true
      getSocialPersonInfo(id)
        .then((res) => {
          this.confirmLoading = false
          if (res.success) {
            const { result } = res
            this.socialPersonAddVO = result
            console.log(res);
          } else {
            this.$message.warn(res.message)
          }
        })
        .catch((e) => {
          this.$message.warn('请求失败！')
          this.confirmLoading = false
        })
    },
    // 监听路由变化
    getRouteQuery($route) {
      if ($route.params && Object.keys($route.params).length > 0) {
        let params = $route.params
        if (params.id) {
          this.id = params.id
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.contain {
  background-color: #fff;
  padding: 24px;
}
.component-action {
  margin: 20px 32px;
}
</style>
